<template>
  <div class="blog_publish">
    <div class="blog_publish_crumbs">
      <span @click="toaddress">孵化社区&nbsp;</span>/
      <span>发布动态</span>
    </div>
    <div class="blog_title">
      <!-- <span class="blog_title_span">文章标题:</span> -->
      <!-- <el-input v-model="blog.title"></el-input> -->
      <el-input
        size="small"
        placeholder="请输入文章标题"
        v-model="blog.title"
        clearable
      >
      </el-input>
    </div>

    <!-- <span>内容:</span> -->
    <quill-editor
      v-model="blog.content"
      ref="myQuillEditor"
      :options="editorOption"
      @blur="onEditorBlur($event)"
      @focus="onEditorFocus($event)"
      @change="onEditorChange($event)"
    >
    </quill-editor>

    <div class="blog_cover">
      <span class="blog_cover_span">封面图片：</span>

      <el-upload
        accept=".jpg,.jpeg,.png"
        class="cover-uploader"
        action="#"
        :show-file-list="false"
        :on-change="changeHandle"
        :auto-upload="true"
        :http-request="upload_avatar1"
      >
        <img
          v-if="blog.coverPicture"
          :src="blog.coverPicture"
          class="avatar"
          style="width: 15rem"
        />

        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        <p slot="tip" class="el-upload__tip" style="color: #909399">
          建议750*420，小于300kb，支持JPG、PNG格式
        </p>
      </el-upload>

      <el-input
        type="textarea"
        placeholder="摘要,若不填写将自动摘取文章开头..."
        v-model="blog.description"
        maxlength="100"
        show-word-limit
      >
      </el-input>
    </div>
    <div>
      <span>文章类型：</span>
      <el-button
        @click="blog.typeId = item.id"
        size="small"
        v-for="item in Article_Type_list"
        :key="item.id"
        >{{ item.name }}</el-button
      >

      <!-- <el-button size="small">评论</el-button> -->
    </div>
    <div class="publish_blog_bottom">
      <span class="publish_blog_bottom_span">共{{ TiLength }}字</span>
      <el-button
        class="publish_blog_bottom_button"
        type="primary"
        round
        @click="publish_blog"
        >发布动态</el-button
      >
    </div>
    <el-upload
      accept=".jpg,.jpeg,.png"
      class="avatar-uploader"
      action="#"
      name="img"
      :show-file-list="false"
      :on-change="changeHandle"
      :auto-upload="true"
      :http-request="upload_avatar"
    >
    </el-upload>
  </div>
</template>

<script>
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import COS from "cos-js-sdk-v5";

// import { ImageDrop } from "quill-image-drop-module";
// import ImageResize from "quill-image-resize-module";
// Quill.register("modules/imageDrop", ImageDrop);
// Quill.register("modules/imageResize", ImageResize);

export default {
  props: {},
  components: { quillEditor },
  data() {
    return {
      imgfile: "",
      Article_Type_list: [],
      blog: {
        title: "",
        content: ``,
        coverPicture: "",
        description: "",
        typeId: "",
      },
      TiLength: 0,
      editorOption: {
        placeholder: "文章内容",
        modules: {
          history: {
            delay: 1000,
            maxStack: 50,
            userOnly: false,
          },
          toolbar: {
            container: [
              ["bold", "italic", "underline", "strike"], //加粗，斜体，下划线，删除线
              ["blockquote", "code-block"], //引用，代码块
              [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
              [{ list: "ordered" }, { list: "bullet" }], //列表
              [{ script: "sub" }, { script: "super" }], // 上下标
              [{ indent: "-1" }, { indent: "+1" }], // 缩进
              [{ direction: "rtl" }], // 文本方向
              [{ size: ["small", false, "large", "huge"] }], // 字体大小
              [{ header: [1, 2, 3, 4, 5, 6, false] }], //几级标题
              [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
              [{ font: [] }], //字体
              [{ align: [] }], //对齐方式
              ["clean"], //清除字体样式
              ["image"],
              //上传图片、上传视频
            ],
            handlers: {
              image: function (value) {
                console.log(value);
                if (value) {
                  // 调用element的图片上传组件
                  document.querySelector(".avatar-uploader input").click();
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
        },
      },
    };
  },
  methods: {
    toaddress() {
      this.$router.push("/home/Team/Team_Incubation_community");
    },
    changeHandle(file) {
      this.imgFile = file;
    },
    async upload_avatar() {
      // 创建COS实例  获取签名
      //这里写你们后端提供的请求接口即可，这里调用的接口是为了获取tmpSecretId、tmpSecretKey、sessionToken、expiredTime这些值
      const { data: res1 } = await this.$http({
        headers: { "Content-Type": "application/json;charset=UTF-8" },
        method: "get",
        url: "/api/upload/getSecretKey",
      });

      const data = res1.credentials;
      const cos = new COS({
        // 必选参数
        getAuthorization: (options, callback) => {
          const obj = {
            TmpSecretId: data.tmpSecretId,
            TmpSecretKey: data.tmpSecretKey,
            XCosSecurityToken: data.sessionToken,
            StartTime: res1.startTime, // 时间戳，单位秒，如：1580000000
            ExpiredTime: res1.expiredTime, // 时间戳，单位秒，如：1580000900
          };
          callback(obj);
        },
      });

      // 上传图片  其中Bucket 和 Region找你们负责人拿，Bucke和Region是由公司负责人使用公司账户，登入腾讯云，获取回来的。
      //key 在前面加上路径写法可以生成文件夹

      cos.putObject(
        {
          Bucket: "fuhuaqi-1311373154" /* 必须 */,
          Region: "ap-guangzhou" /* 存储桶所在地域，必须字段 */,
          Key: "/blog/" + new Date().getTime() + this.imgFile.name /* 必须 */,
          StorageClass: "STANDARD",
          Body: this.imgFile.raw, // 上传文件对象
          onProgress: (progressData) => {},
        },
        (err, data) => {
          // 将上传后的封面进行路径拼接保存到本地
          let quill = this.$refs.myQuillEditor.quill;
          const url = "https://" + data.Location;
          if (url) {
            // if (name == "/blog/") {
            let length = quill.getSelection().index;
            // 插入图片，res为服务器返回的图片链接地址
            quill.insertEmbed(length, "image", url);
            // 调整光标到最后
            quill.setSelection(length + 1);
          }
        }
      );
    },
    async upload_avatar1() {
      // 创建COS实例  获取签名
      //这里写你们后端提供的请求接口即可，这里调用的接口是为了获取tmpSecretId、tmpSecretKey、sessionToken、expiredTime这些值
      const { data: res1 } = await this.$http({
        headers: { "Content-Type": "application/json;charset=UTF-8" },
        method: "get",
        url: "/api/upload/getSecretKey",
      });

      const data = res1.credentials;
      const cos = new COS({
        // 必选参数
        getAuthorization: (options, callback) => {
          const obj = {
            TmpSecretId: data.tmpSecretId,
            TmpSecretKey: data.tmpSecretKey,
            XCosSecurityToken: data.sessionToken,
            StartTime: res1.startTime, // 时间戳，单位秒，如：1580000000
            ExpiredTime: res1.expiredTime, // 时间戳，单位秒，如：1580000900
          };
          callback(obj);
        },
      });

      // 上传图片  其中Bucket 和 Region找你们负责人拿，Bucke和Region是由公司负责人使用公司账户，登入腾讯云，获取回来的。
      //key 在前面加上路径写法可以生成文件夹

      cos.putObject(
        {
          Bucket: "fuhuaqi-1311373154" /* 必须 */,
          Region: "ap-guangzhou" /* 存储桶所在地域，必须字段 */,
          Key:
            "/blog/cover/" +
            new Date().getTime() +
            this.imgFile.name /* 必须 */,
          StorageClass: "STANDARD",
          Body: this.imgFile.raw, // 上传文件对象
          onProgress: (progressData) => {},
        },
        (err, data) => {
          // 将上传后的封面进行路径拼接保存到本地

          const url = "https://" + data.Location;
          if (url) {
            this.blog.coverPicture = url;
          }
        }
      );
    },
    // 准备编辑器
    onEditorReady(editor) {},
    // 失去焦点事件
    onEditorBlur() {},
    // 获得焦点事件
    onEditorFocus() {},
    // 内容改变事件
    onEditorChange(quill) {
      this.blog.content = quill.html;
      console.log(this.blog.content);
      this.TiLength = quill.quill.getLength() - 1;
    },
    async publish_blog() {
      if (this.blog.title == "") {
        this.$message.error("文章标题不能为空");
        return;
      }
      if (this.blog.content == "") {
        this.$message.error("文章内容不能为空");
        return;
      }
      if (this.blog.coverPicture == "") {
        this.$message.error("封面图片不能为空");
        return;
      }
      if (this.blog.description == "") {
        this.$message.error("文章摘要不能为空");
        return;
      }
      if (this.blog.typeId == "") {
        this.$message.error("文章类型不能为空");
        return;
      }

      const self = this;
      const { data: res } = await this.$http({
        headers: { "Content-Type": "application/json;charset=UTF-8" },
        method: "post",
        url: "/api/team/article/addArticle",
        data: self.blog,
      });
      console.log(res);
      if (res.code == 200) {
        this.$message.success(res.msg);
        for (var i in this.blog) {
          this.blog[i] = ``;
        }
      } else {
        this.$message.error(res.msg);
      }
    },
  },
  async created() {
    this.$emit("name", "/home/Team/Team_Incubation_community");

    const { data: res } = await this.$http({
      headers: { "Content-Type": "application/json;charset=UTF-8" },
      method: "get",
      url: "/api/team/article/getArticleType",
    });
    this.Article_Type_list = res.msg;
  },
};
</script>

<style lang="less">
.blog_publish {
  display: flex;
  // background-color: rgb(201, 26, 26);
  width: 100%;
  height: 91.5%;
  flex-direction: column;
  overflow: auto;
  position: relative;

  .blog_publish_crumbs {
    display: flex;
    margin: 10px;
    margin-left: 20px;

    span:nth-child(1) {
      color: rgb(127, 127, 127);
      cursor: pointer;
    }
    span:nth-child(2) {
      color: rgb(0, 110, 255);
      cursor: pointer;
    }
    span:hover {
      color: rgb(0, 110, 255);
    }
  }
}
.blog_title {
  display: flex;
  width: 100%;
  height: 50px;
  .blog_title_span {
    // font-size: 23px;
    width: 120px;
    height: 50px;
    display: flex;
    line-height: 50px;
  }
  .el-input {
    height: 50px;
    line-height: 50px;
  }
}

.blog_cover {
  width: 100%;

  margin-top: 200px;
  display: flex;
  justify-content: space-between;
  .blog_cover_span {
    width: 120px;
  }
  // .el-textarea{
  //     margin-left: 50px;
  //   width: 50%;
  //   height: 180px !important;
  // }
  .el-textarea__inner {
    margin-left: 50px;
    width: 93%;
    height: 200px !important;
  }

  .cover-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .cover-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 15rem;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
.publish_blog_bottom {
  // width: 88%;
  height: 50px;
  position: fixed;
  background-color: #fff;
  // margin: 0 auto;
  left: 250px;
  right: 10px;
  bottom: 0;
  display: flex;
  justify-content: space-between;
  border-top: 1px solid rgb(237, 237, 237);
  .publish_blog_bottom_span {
    height: 7%;
    display: flex;
    line-height: 50px;
    font-size: 20px;
  }
  .publish_blog_bottom_button {
    height: 40px;
    margin: auto 0px;
    background-color: rgb(0, 110, 255);
    font-size: 22px;
  }
}
.blog_publish::-webkit-scrollbar-thumb {
  border-radius: 3px;
  background: #fff;
}
.blog_publish::-webkit-scrollbar {
  width: 6px;
}
.blog_publish:hover::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2);
}
</style>